/*
 * @Author: your name
 * @Date: 2021-09-11 19:41:37
 * @LastEditTime: 2021-09-12 11:09:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bigdatavue\src\ntils\excel.ts
 */
import xlsx from 'xlsx'
import type { WorkBook, JSON2SheetOpts, WritingOptions, BookType } from 'xlsx'

const { utils, writeFile } = xlsx
const DEF_FILE_NAME = 'excel-list.xlsx'
interface JsonToSheet<T = any> {
    data: T[];
    header?: T;
    filename?: string;
    json2sheetOpts?: JSON2SheetOpts;
    write2excelOpts?: WritingOptions;
  }
export function jsonToSheetXlsx<T = any>({
    data,
    header,
    filename = DEF_FILE_NAME,
    json2sheetOpts = {},
    write2excelOpts = { bookType: 'xlsx' },
}:JsonToSheet<T>) {
    const arrData = [...data]
    // 如果头部存在将头部存入
    if (header) {
        arrData.unshift(header),
        json2sheetOpts.skipHeader = true
    }
    // 开始转译
    const worksheet = utils.json_to_sheet(arrData, json2sheetOpts)
    // 导出类型
    const workbook: WorkBook = {
        SheetNames: [filename],
        Sheets: {
            [filename]: worksheet,
        },
    }
    writeFile(workbook, filename, write2excelOpts)  
}

export const arrHeader = function (datas) {
    return datas.map((column) => column.title)
}
export const arrData = function (datas) {
    return datas.map((item) => Object.keys(item).map((key) => item[key]))
}